import { Button } from 'antd';
import { ChangeEvent, FC, useRef, useState } from 'react';
import csvSample from './csv-sample.png';
import { FeatureManager } from '@amcax/base';
import { DESIGN_TABLE_EVENTS } from '@app-base/common/Constants';

interface CsvFileImporterProps {
  onFileSelected: (file: File) => void;
}

export const CsvFileImporter: FC<CsvFileImporterProps> = ({
  onFileSelected,
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [fileName, setFileName] = useState('');

  const handleButtonClick = () => {
    if (!FeatureManager.isFeatureEnabled('electron-show-port')) {
      (window as any)?.electronCenter?.emit(
        DESIGN_TABLE_EVENTS.IMPORT_DESIGN_TABLE,
        null,
      );
      return;
    }
    fileInputRef.current?.click();
  };

  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setFileName(file.name);
      onFileSelected(file);
    }
  };

  return (
    <div className='w-full max-w-md mx-auto select-none'>
      <div className='flex items-center space-x-2'>
        <input
          type='text'
          className='flex-1 border border-gray-300 rounded px-3 py-2 bg-gray-100 text-gray-700 focus:outline-none'
          value={fileName}
          placeholder='请选择 CSV 文件'
          readOnly
        />
        <Button
          type='primary'
          ghost
          onClick={handleButtonClick}
        >
          选择文件
        </Button>
        <input
          ref={fileInputRef}
          type='file'
          accept='.csv'
          className='hidden'
          onChange={handleFileChange}
        />
      </div>
      <div className='mt-2 text-gray-500'>
        只支持.csv文件。列代表不同的参数，首行为参数名称，第二行开始，每行代表一个系列的参数值。
      </div>
      <div className='mt-2'>示意图：</div>
      <div>
        <img
          src={csvSample}
          alt='CSV 示例'
          className='w-full max-w-md mx-auto my-4'
        />
      </div>
    </div>
  );
};
